<script setup lang="ts">
	import { reactive, ref } from 'vue'
	import { FormInstance, FormRules, ElMessage } from 'element-plus'
	import { addOrUpdateCarouselsApi } from '@/api/modules/config'
	import Upload from '@/components/Upload/index.vue'
	// import { Carousels } from '@/api/interface/home'
	// import UploadCover from '@/components/UploadCover/index.vue'

	// * 显示 隐藏
	// 定义props
	const { type = 'add', reload } = defineProps<{
		type: 'add' | 'update'
		reload: Function
	}>()

	// 显示 / 隐藏
	const visible = ref(false)

	// 打开弹窗
	const dialogOpen = () => {
		visible.value = true
	}

	// 关闭弹窗
	const dialogClose = () => {
		formRef.value.resetFields()
		ruleForm.value = { carouselUrl: '', redirectUrl: '', carouselRank: 0 }
		visible.value = false
	}

	// * 表单数据收集
	// 表单实例
	const formRef = ref<FormInstance>(null)

	// 校验规则
	const rules: FormRules = reactive({
		carouselUrl: [{ required: true, message: '图片不能为空', trigger: ['change'] }],
		carouselRank: [{ required: true, message: '排序不能为空', trigger: ['change'] }]
	})

	// 收集表单
	const ruleForm = ref({
		carouselUrl: '',
		redirectUrl: '',
		carouselRank: 0
	})

	// 提交数据
	const submitForm = async () => {
		// 验证表单
		await formRef.value.validate()
		// 判断操作类型 添加操作 | 修改操作
		await addOrUpdateCarouselsApi(ruleForm.value)
		ElMessage.success(type === 'update' ? '修改成功' : '添加成功')
		dialogClose()
		// 调用父组件传递的方法 $parent
		reload()
	}

	// 抛出实例方法
	defineExpose({
		dialogOpen,
		dialogClose,
		ruleForm
	})
</script>

<template>
	<el-dialog destroy-on-close :title="type === 'add' ? '添加轮播图' : '修改轮播图'" v-model="visible" :before-close="dialogClose">
		<el-form :rules="rules" :model="ruleForm" ref="formRef" label-width="100px" class="swiper-form">
			<el-form-item label="图片" prop="carouselUrl">
				<Upload v-model:a="ruleForm.carouselUrl" />
			</el-form-item>
			<el-form-item label="跳转链接" prop="redirectUrl">
				<!-- <Upload v-model:a="ruleForm.redirectUrl" /> -->
				<el-input type="text" v-model="ruleForm.redirectUrl" />
			</el-form-item>
			<el-form-item label="排序值" prop="carouselRank">
				<el-input-number v-model="ruleForm.carouselRank" :min="1" :max="200" :precision="0" />
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="dialogClose">取 消</el-button>
				<el-button type="primary" @click="submitForm">确 定</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<style scoped lang="scss"></style>
